package com.longe.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

@Controller
public class UserController {

    @RequestMapping("login")
    public String login(String userName, String password){

        Subject current = SecurityUtils.getSubject();
        //判断该subject是否认证
        if(!current.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
            try {
                current.login(token);
            } catch (UnknownAccountException e) {
                throw new RuntimeException("账号不存在");
            } catch (IncorrectCredentialsException e) {
                throw new RuntimeException("密码不正确");
            } catch (Exception e) {
                throw new RuntimeException("内部错误");
            }
        }

        Object principal = current.getPrincipal();
        System.err.println("当前用户为：" + principal);

        /**查看session中存储了什么**/
        Session session = current.getSession();
        Collection<Object> attributeKeys = session.getAttributeKeys();
        for (Object attributeKey : attributeKeys) {
            System.err.println("sessionKey: " + attributeKey + ", sessionValue: " + session.getAttribute(attributeKey));
        }

        System.out.println("sessionId: " + session.getId());
        return "home";
    }

    @RequestMapping("logout")
    public String logout(){

        Subject current = SecurityUtils.getSubject();
        current.logout();

        return "/";
    }
}
